"""
权限、组、角色、应用、岗位、菜单
"""
from rest_framework import viewsets
from rest_framework.renderers import JSONRenderer
from rest_framework.pagination import PageNumberPagination
from rest_framework.views import APIView
from rest_framework.response import Response
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from .Serializers import *
from .models import *
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework.permissions import IsAuthenticated, IsAdminUser, AllowAny, BasePermission
from django.contrib.auth import authenticate
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter
from .filters import *

schema_view = get_schema_view(
    openapi.Info(
        title="超灵活框架API",
        default_version='v1.0',
        description="超灵活框架API",
        terms_of_service="https://www.example.com/policies/terms/",
        contact=openapi.Contact(email="contact@example.com"),
        license=openapi.License(name="BSD License"),
    ),
    public=True,
    permission_classes=[AllowAny],
)


# 生成uuid
def get_uuid():
    return str(uuid.uuid4())


class CustomPagination(PageNumberPagination):
    page_size = 20  # 每页显示的数量
    page_size_query_param = 'page_size'  # URL 参数中控制每页数量的参数名
    max_page_size = 100  # 最大的每页数量限制


class CustomRenderer(JSONRenderer):
    def render(self, data, accepted_media_type=None, renderer_context=None):
        # 修改返回的 JSON 数据格式

        code = renderer_context['response'].status_code
        if code == 200 or code == 201 or code == 204:
            modified_data = {
                "code": 1,
                "data": data,
                "status_code": code
            }
        elif code == 403:
            modified_data = {
                "code": -1,
                "data": data,
                "status_code": code
            }
        else:
            modified_data = {
                "code": -1,
                "data": data,
                "status_code": code
            }

        return super().render(modified_data, accepted_media_type, renderer_context)


class Login(APIView):
    """
    登录
    """
    renderer_classes = [CustomRenderer]

    # authentication_classes = []
    # permission_classes = []

    def post(self, request):

        try:
            username = request.data.get('username')
            password = request.data.get('password')
            user = authenticate(request, username=username, password=password)
            if user is None:
                return Response(status=401, data={"message": "user is not exist!"})
            refresh = RefreshToken.for_user(user)
            data = {
                "id": user.id,
                "token": str(refresh.access_token),
                "username": user.username,
            }
            return Response(data=data, status=200)



        except Exception as e:
            data = {
                "message": str(e),
                "res": '获取token失败！'
            }
            return Response(data, status=404)


class ModuleView(viewsets.ModelViewSet):
    """应用管理"""
    # authentication_classes = [JWTAuthentication]
    # permission_classes = [IsAuthenticated]
    queryset = ModulesModel.objects.all()
    serializer_class = ModuleSerializer
    renderer_classes = [CustomRenderer]
    filterset_class = ModulesFilter

    def create(self, request, *args, **kwargs):
        request.data['id'] = get_uuid()
        return super().create(request, *args, **kwargs)


class MenusView(viewsets.ModelViewSet):
    """菜单管理"""
    # authentication_classes = [JWTAuthentication]
    # permission_classes = [IsAuthenticated]
    queryset = MenusModel.objects.all()
    serializer_class = MenusModelSerializer
    renderer_classes = [CustomRenderer]
    filterset_class = MenusFilter

    # search_fields = ['username']  # 可搜索的字段

    def create(self, request, *args, **kwargs):
        request.data['id'] = get_uuid()
        return super().create(request, *args, **kwargs)


class UsersView(viewsets.ModelViewSet):
    """用户管理"""

    # authentication_classes = [JWTAuthentication]
    # permission_classes = [IsAuthenticated]
    queryset = User.objects.all()
    serializer_class = UserSerializer
    renderer_classes = [CustomRenderer]
    # filter_backends = (DjangoFilterBackend, SearchFilter)
    filterset_class = UsersFilter

    # search_fields = ['username']  # 可搜索的字段

    def create(self, request, *args, **kwargs):
        request.data['id'] = get_uuid()
        return super().create(request, *args, **kwargs)


class AdmDivCodeView(viewsets.ModelViewSet):
    """用户管理"""

    # authentication_classes = [JWTAuthentication]
    # permission_classes = [IsAuthenticated]
    queryset = AdmDivCodeModel.objects.all()
    serializer_class = AdmDivCodeSerializer
    renderer_classes = [CustomRenderer]
    # filter_backends = (DjangoFilterBackend, SearchFilter)
    filterset_class = AdmDivCodeFilter

    # search_fields = ['username']  # 可搜索的字段

    def create(self, request, *args, **kwargs):
        request.data['id'] = get_uuid()
        return super().create(request, *args, **kwargs)


class GropView(viewsets.ModelViewSet):
    # authentication_classes = [JWTAuthentication]
    # permission_classes = [IsAuthenticated]
    queryset = GropModel.objects.all()
    serializer_class = GropSerializer
    renderer_classes = [CustomRenderer]

    def create(self, request, *args, **kwargs):
        request.data['id'] = get_uuid()
        return super().create(request, *args, **kwargs)


class InstitutionsView(viewsets.ModelViewSet):
    # authentication_classes = [JWTAuthentication]
    # permission_classes = [IsAuthenticated]
    queryset = InstitutionsModel.objects.all()
    serializer_class = InstitutionsSerializer
    renderer_classes = [CustomRenderer]
    filterset_class = InstitutionsFilter

    def create(self, request, *args, **kwargs):
        request.data['id'] = get_uuid()
        return super().create(request, *args, **kwargs)


class ClassificationView(viewsets.ModelViewSet):
    # authentication_classes = [JWTAuthentication]
    # permission_classes = [IsAuthenticated]
    queryset = ClassificationModel.objects.all()
    serializer_class = ClassificationSerializer
    renderer_classes = [CustomRenderer]

    def create(self, request, *args, **kwargs):
        request.data['id'] = get_uuid()
        return super().create(request, *args, **kwargs)


class InstitutionsTypesView(viewsets.ModelViewSet):
    # authentication_classes = [JWTAuthentication]
    # permission_classes = [IsAuthenticated]
    queryset = InstitutionsTypesModel.objects.all()
    serializer_class = InstitutionsTypesSerializer
    renderer_classes = [CustomRenderer]

    def create(self, request, *args, **kwargs):
        request.data['id'] = get_uuid()
        return super().create(request, *args, **kwargs)


class InstitutionsSelectsView(viewsets.ModelViewSet):
    # authentication_classes = [JWTAuthentication]
    # permission_classes = [IsAuthenticated]
    queryset = InstitutionsSelectModel.objects.all()
    serializer_class = InstitutionsSelectSerializer
    renderer_classes = [CustomRenderer]

    def create(self, request, *args, **kwargs):
        request.data['id'] = get_uuid()
        return super().create(request, *args, **kwargs)


class MenusPermissionsView(viewsets.ModelViewSet):
    # authentication_classes = [JWTAuthentication]
    # permission_classes = [IsAuthenticated]
    queryset = MenusPermissionsModel.objects.all()
    serializer_class = MenusPermissionsSerializer
    renderer_classes = [CustomRenderer]

    def create(self, request, *args, **kwargs):
        request.data['id'] = get_uuid()
        return super().create(request, *args, **kwargs)


class FlowView(viewsets.ModelViewSet):
    # authentication_classes = [JWTAuthentication]
    # permission_classes = [IsAuthenticated]

    queryset = FlowModel.objects.all()
    serializer_class = FlowSerializer
    renderer_classes = [CustomRenderer]
    filterset_class = FlowFilter

    def create(self, request, *args, **kwargs):
        request.data['id'] = get_uuid()
        return super().create(request, *args, **kwargs)


class ImagesView(viewsets.ModelViewSet):
    # authentication_classes = [JWTAuthentication]
    # permission_classes = [IsAuthenticated]

    queryset = ImageModel.objects.all()
    serializer_class = ImagesSerializer
    renderer_classes = [CustomRenderer]

    def create(self, request, *args, **kwargs):
        request.data['id'] = get_uuid()
        return super().create(request, *args, **kwargs)


class UserGropView(viewsets.ModelViewSet):
    # authentication_classes = [JWTAuthentication]
    # permission_classes = [IsAuthenticated]

    queryset = UserGropModel.objects.all()
    serializer_class = UserGropModelSerializer
    renderer_classes = [CustomRenderer]

    def create(self, request, *args, **kwargs):
        request.data['id'] = get_uuid()
        return super().create(request, *args, **kwargs)


class DataBaseView(viewsets.ModelViewSet):
    """数据库管理"""
    # authentication_classes = [JWTAuthentication]
    # permission_classes = [IsAuthenticated]

    queryset = DataBaseModel.objects.all()
    serializer_class = DataBaseSerializer
    renderer_classes = [CustomRenderer]
    filterset_class = DataBaseFilter

    def create(self, request, *args, **kwargs):
        request.data['id'] = get_uuid()
        return super().create(request, *args, **kwargs)
